const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const cors = require('koa-cors');
const multer = require('@koa/multer');
const path = require('path');
const fs = require('fs');
const config = require('./config');
const pool = require('./db');

// 文件上传配置
const upload = multer({
  dest: 'uploads/',
  limits: { fileSize: 10 * 1024 * 1024 }
});

const app = new Koa();
const router = new Router();

// 初始化数据库表
const initDB = async () => {
  const conn = await pool.getConnection();
  try {
    // 歌曲表（用于存储歌名）
    await conn.query(`
      CREATE TABLE IF NOT EXISTS songs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL UNIQUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      )`);
    
    // 歌手表（用于存储原唱）
    await conn.query(`
      CREATE TABLE IF NOT EXISTS songers (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL UNIQUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      )`);
    
    // 音乐表（用于存储完整的音乐信息）
    await conn.query(`
      CREATE TABLE IF NOT EXISTS music (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        artist VARCHAR(255) NOT NULL,
        lyrics TEXT,
        song_url VARCHAR(255) NOT NULL,
        cover_url VARCHAR(255),
        duration INT DEFAULT 0,
        play_count INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      )`);
    
    // 播放列表表
    await conn.query(`
      CREATE TABLE IF NOT EXISTS playlists (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        description TEXT,
        cover_url VARCHAR(255),
        is_public BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      )`);
    
    // 播放列表歌曲关联表
    await conn.query(`
      CREATE TABLE IF NOT EXISTS playlist_songs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        playlist_id INT NOT NULL,
        song_id INT NOT NULL,
        sort_order INT DEFAULT 0,
        added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (playlist_id) REFERENCES playlists(id) ON DELETE CASCADE,
        FOREIGN KEY (song_id) REFERENCES songs(id) ON DELETE CASCADE,
        UNIQUE KEY unique_playlist_song (playlist_id, song_id)
      )`);
    
    // 用户收藏表
    await conn.query(`
      CREATE TABLE IF NOT EXISTS user_favorites (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id VARCHAR(100) NOT NULL,
        song_id INT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (song_id) REFERENCES songs(id) ON DELETE CASCADE,
        UNIQUE KEY unique_user_song (user_id, song_id)
      )`);
    
    // 播放历史表
    await conn.query(`
      CREATE TABLE IF NOT EXISTS play_history (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id VARCHAR(100) NOT NULL,
        song_id INT NOT NULL,
        played_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (song_id) REFERENCES songs(id) ON DELETE CASCADE
      )`);
  } finally {
    conn.release();
  }
};

// 初始化数据库并确保连接成功
initDB().then(() => {
  console.log('数据库连接池已导入:', pool !== undefined);
}).catch(err => {
  console.error('数据库初始化失败:', err);
  process.exit(1);
});

// 导入路由
const musicRouter = require('./routes/music');
const playlistRouter = require('./routes/playlist');
const favoriteRouter = require('./routes/favorite');
const historyRouter = require('./routes/history');
const uploadRouter = require('./routes/upload');
const songsRouter = require('./routes/songs');
const songersRouter = require('./routes/songers');

// 错误处理中间件（必须在最前面）
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    console.error('服务器错误:', err);
    ctx.status = err.status || 500;
    ctx.body = { code: -1, message: err.message };
  }
});

// 中间件配置
app.use(cors({
  origin: '*',
  credentials: false,
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept']
}));
app.use(bodyParser());

// 静态文件服务 - 提供 uploads 目录下的文件访问
const uploadsPath = path.join(__dirname, 'uploads');
const staticPath = path.join(__dirname, '..', 'static');

app.use(async (ctx, next) => {
  if (ctx.path.startsWith('/uploads/')) {
    const filePath = path.join(uploadsPath, ctx.path.replace('/uploads/', ''));
    try {
      if (fs.existsSync(filePath)) {
        ctx.type = path.extname(filePath);
        ctx.body = fs.createReadStream(filePath);
        return;
      }
    } catch (err) {
      console.error('读取uploads文件失败:', err);
    }
  }
  await next();
});

// 静态文件服务 - 提供 static 目录下的文件访问（用于本地音频文件）
app.use(async (ctx, next) => {
  if (ctx.path.startsWith('/static/')) {
    const filePath = path.join(staticPath, ctx.path.replace('/static/', ''));
    try {
      if (fs.existsSync(filePath)) {
        ctx.type = path.extname(filePath);
        ctx.body = fs.createReadStream(filePath);
        return;
      }
    } catch (err) {
      console.error('读取static文件失败:', err);
    }
  }
  await next();
});

// 添加根路由，用于测试
router.get('/', async (ctx) => {
  ctx.body = { 
    message: '音乐API服务器正在运行',
    status: 'ok',
    timestamp: new Date().toISOString()
  };
});

// 添加健康检查路由
router.get('/health', async (ctx) => {
  ctx.body = { 
    status: 'healthy',
    uptime: process.uptime(),
    timestamp: new Date().toISOString()
  };
});

// 通过主 router 挂载上传路由（避免 app.use 传入非中间件引发错误）
router.use('/api/upload', uploadRouter.routes(), uploadRouter.allowedMethods());
console.log('✓ Upload 路由已注册: /api/upload');

// 使用其他路由
console.log('开始注册路由...');
router.use('/api/music', musicRouter.routes(), musicRouter.allowedMethods());
console.log('✓ Music 路由已注册: /api/music');
router.use('/api/playlist', playlistRouter.routes(), playlistRouter.allowedMethods());
console.log('✓ Playlist 路由已注册: /api/playlist');
router.use('/api/favorite', favoriteRouter.routes(), favoriteRouter.allowedMethods());
console.log('✓ Favorite 路由已注册: /api/favorite');
router.use('/api/history', historyRouter.routes(), historyRouter.allowedMethods());
console.log('✓ History 路由已注册: /api/history');
router.use('/api/songs', songsRouter.routes(), songsRouter.allowedMethods());
console.log('✓ Songs 路由已注册: /api/songs');
router.use('/api/songers', songersRouter.routes(), songersRouter.allowedMethods());
console.log('✓ Songers 路由已注册: /api/songers');

// 注册路由到app
app.use(router.routes()).use(router.allowedMethods());
console.log('✓ 所有路由已注册到应用');

// 打印所有注册的路由
console.log('已注册的路由:');
router.stack.forEach((layer) => {
  if (layer.path) {
    console.log(`- ${layer.path}`);
  }
});

// 打印所有注册的路由进行诊断
console.log('--- Registered Routes ---');
router.stack.forEach(function (r) {
    if (r.path && r.methods.length > 0) {
        console.log(r.methods.join(', ') + ' ' + r.path);
    }
});
console.log('-------------------------');

// 启动服务器
app.listen(config.PORT, '0.0.0.0', () => {
  console.log(`服务器运行在 http://localhost:${config.PORT}`);
  console.log(`网络访问地址: http://172.29.99.148:${config.PORT}`);
  console.log('服务器已启动，可以接收请求');
});

module.exports = { app, pool, upload };